package com.simon.api.recommond;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by changf on 2017/7/7.
 */
public class RedisService {

    static final String CART_PREFIX="cart:";
    static final String ITEM_RECOMMEND_POOL="recommond:pool:";
    static final String RECOMMEND_USER_FREFIX="recommond:user:";

    Jedis jedis = new Jedis("192.168.112.12", 6379);

    public void addToCart(String userName,String newItem,int incr){

        //首先将信息存放到hset

        if(!jedis.hexists(CART_PREFIX+userName,newItem)){

            Set<String> cartItems = getCartItems(userName);
            //如果是新商品。则需要创建一个推荐池
            for(String itemName:cartItems){
                //添加老的
                jedis.zincrby(ITEM_RECOMMEND_POOL+itemName,1,newItem);
                //新的也需要添加
                jedis.zincrby(ITEM_RECOMMEND_POOL+newItem,1,itemName);
            }


        }
        jedis.hincrBy(CART_PREFIX+userName,newItem,incr);
    }

    /**
     * 获取购物车中的品类
     * @param userName
     * @return
     */
    public Set<String> getCartItems(String userName){
        Set<String> hkeys = jedis.hkeys(CART_PREFIX + userName);
        return hkeys;
    }


    /**
     * 获取购物车详情
     * @param userName
     * @return
     */
    public Map<String,String> getCart(String userName){

        Map<String, String> stringStringMap = jedis.hgetAll(CART_PREFIX + userName);

        return stringStringMap;
    }


    public Map<String ,Double> getRecommend(String userName){
        Set<String> cartItems = getCartItems(userName);

        for(String item:cartItems){
            jedis.zunionstore(RECOMMEND_USER_FREFIX+userName,ITEM_RECOMMEND_POOL+item);

        }
        //过滤购物车中已有的购物项
        //获取长度
        Long zcard = jedis.zcard(RECOMMEND_USER_FREFIX + userName);
        Set<String> zrange = jedis.zrange(RECOMMEND_USER_FREFIX + userName, 0, zcard);
        for(String ss:zrange){
            if(cartItems.contains(ss))continue;
            //不包含那就组合成推荐的
            jedis.zadd(RECOMMEND_USER_FREFIX+"real:" + userName,jedis.zscore(RECOMMEND_USER_FREFIX + userName,ss),ss);



        }
        Set<Tuple> tuples = jedis.zrevrangeWithScores(RECOMMEND_USER_FREFIX+"real:" + userName, 0, 3);
        Map<String,Double> recommendsMap=new HashMap<String, Double>();
        for(Tuple tuple:tuples){
            recommendsMap.put(tuple.getElement(),tuple.getScore());
        }

        return recommendsMap;
    }
}
